#include "message.h"
#include "asynevent.h"
#include "event-internal.h"

MessageHandler::~MessageHandler()
{
	event_base * ev_base = AsynEventFramework::Instance()->GetEventBase();

	std::set<Message*>::iterator iter = message_set_.begin();
	std::set<Message*>::iterator end = message_set_.end();
	for(; iter!=end; ++iter){
		event_deferred_cb_cancel( &ev_base->defer_queue, &((*iter)->deferred_));
	}

}

static void run_callback(struct deferred_cb *d, void *user_pointer)
{
	Message * pMsg = NTDTIL_UPCAST(d, Message, deferred_);
	if( pMsg != NULL ){
		if( pMsg->phandler ){
			pMsg->phandler->OnMessage(pMsg);
		}else{
			if( MQID_DISPOSE == pMsg->message_id ){
				delete pMsg->pdata;
			}
		}
	}
	delete pMsg;
}


void Message::Post()
{
	event_base * ev_base = AsynEventFramework::Instance()->GetEventBase();

	event_deferred_cb_init(&deferred_, run_callback, NULL);
	event_deferred_cb_schedule(	&ev_base->defer_queue, &deferred_);
}